package tech.ihai.spring.boot.sample.loader;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tech.ihai.spring.boot.sample.loader.bean.CompanyBean;
import tech.ihai.spring.boot.sample.loader.entity.CompanyInfo;
import tech.ihai.spring.boot.sample.loader.entity.TblOrgInfo;
import tech.ihai.spring.boot.sample.loader.repo.CompanyInfoRepo;
import tech.ihai.spring.boot.sample.loader.repo.TblOrgInfoRepo;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Adolphus
 * @description TODO
 * @date 2022/6/15 17:18
 */
@Component
public class LoadDemoData {
    @Autowired
    private CompanyInfoRepo companyInfoRepo;
    @Autowired
    private TblOrgInfoRepo orgInfoRepo;

    @Transactional(rollbackFor = Exception.class)
    public void loadData(String excelPath,int type){
        Map<String,String> orgMap = new HashMap<>();
        EasyExcel.read(excelPath, CompanyBean.class, new PageReadListener<CompanyBean>(dataList->{
            for(CompanyBean row : dataList){
                if("主键ID".equals(row.getId()) || StringUtils.isBlank(row.getId())){
                    continue;
                }
                CompanyInfo companyInfo = new CompanyInfo();
                companyInfo.setName(row.getCompanyName());
                companyInfo.setAddress(row.getCompanyAddress());
                companyInfo.setBussinessNo(row.getBussinessNo());
                companyInfo.setType(type);
                if(!orgMap.containsKey(row.getGrid())){
                    try {
                        TblOrgInfo orgInfo = orgInfoRepo.findById(row.getGrid()).get();
                        orgMap.put(row.getGrid(),orgInfo.getParentorgid());
                    }catch (Exception e) {
                        System.out.println("grid:"+row.getGrid());
                        throw e;
                    }
                }
                companyInfo.setOrgId("");
                companyInfo.setLat(row.getLatitude());
                companyInfo.setLon(row.getLongitude());
                companyInfo.setTel(row.getContactInfo());
                companyInfo.setLegalMan(row.getName());
                companyInfo.setIdNo(row.getIdNo());
                companyInfoRepo.save(companyInfo);
            }
        })).sheet().doRead();
    }

}
